import SwiftUI

// LoginButton
// 登录界面小窗口按钮

struct LoginButton: View {
    @Environment(\.modelContext) private var modelContext
    
    @StateObject private var loginloginRequester = LoginloginRequester()
    
    @State private var isLoginRequesting: Bool = false
    
    @Binding var phoneNumberInput: String
    @Binding var passwordInput: String
    
    @Binding var showRegister: Bool
    
    var body: some View {
        VStack() {
            Button {
                withAnimation {
                    isLoginRequesting.toggle()
                }
                loginloginRequester.request(modelContext, phoneNumberInput, passwordInput)
            } label: {
                Spacer()
                if isLoginRequesting {
                    ProgressView()
                        .progressViewStyle(CircularProgressViewStyle())
                        .tint(.white)
                        .padding(.vertical, 15)
                } else {
                    Text("登录")
                        .foregroundColor(.white)
                        .font(.title2)
                        .padding(.vertical, 12)
                }
                Spacer()
            }
            .disabled(isLoginRequesting)
            .background(.accent)
            .cornerRadius(8)
            
            Button {
                withAnimation {
                    showRegister.toggle()
                }
            } label: {
                Spacer()
                Text("注册")
                    .foregroundColor(.white)
                    .font(.title2)
                    .padding(.vertical, 12)
                Spacer()
            }
            .disabled(isLoginRequesting)
            .background(isLoginRequesting ? .gray : .accent)
            .cornerRadius(8)
        }
        .padding(.horizontal)
        .onChange(of: loginloginRequester.requestStatus) { oldValue, newValue in
            if(oldValue == .requesting && newValue == .finish) {
                isLoginRequesting.toggle()
            }
        }
    }
}

#Preview {
    LoginButton(phoneNumberInput: .constant("18102676918"),
                passwordInput: .constant("jby031216"),
                showRegister: .constant(false))
}
